package main

import (
	"fmt"
	"strconv"
)

type ListNode struct {
	Val  int
	Next *ListNode
}

func (l *ListNode) String() string {
	lnode := l
	str := ""
	for lnode != nil {
		str += strconv.Itoa(lnode.Val)
		lnode = lnode.Next
	}
	return str
}

func main() {
	l1 := strToLink2("243")
	ll1 := strToLink("564")

	fmt.Println(l1, ll1)
	result := addTwoNumbers(l1, ll1)
	fmt.Println(result)

	l1 = swapPairs(l1)
	fmt.Println(l1)
}

func swapPairs(head *ListNode) *ListNode {
	if head == nil {
		return nil
	}

	tmp := head
	for tmp != nil {
		if tmp.Next == nil {
			break
		}

		if tmp.Next != nil {
			node1 := tmp           // 2
			node2 := tmp.Next      // 4
			node3 := tmp.Next.Next //3

			root := node2
			root.Next = node1
			root.Next.Next = node3

			tmp = root
		}

		if tmp.Next.Next != nil {
			tmp = tmp.Next.Next
		}
	}
	return head
}

// 本质是构建链表，在for循环中永远都是2个节点的东西
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	if l1 == nil && l2 == nil {
		return nil
	}

	result := ListNode{0, nil}
	other := &result

	value1, value2 := 0, 0

	for l1 != nil && l2 != nil {
		value2 = (l1.Val + l2.Val + value1) % 10
		value1 = (l1.Val + l2.Val + value1) / 10

		temp := &ListNode{value2, nil}
		other.Next = temp
		other = temp

		l1 = l1.Next
		l2 = l2.Next

		if l1 == nil && l2 == nil {
			break
		}
		if l1 == nil {
			l1 = &ListNode{0, nil}
		}
		if l2 == nil {
			l2 = &ListNode{0, nil}
		}
	}
	if value1 != 0 {
		other.Next = &ListNode{value1, nil}
	}

	return result.Next
}

func strToLink2(str string) *ListNode {
	root := ListNode{0, nil}
	other := &root // 定义一个指针，指向第一个节点

	for i := 0; i < len(str); i++ {
		v2, _ := strconv.Atoi(string(str[i]))
		tmp := ListNode{v2, nil} // 创建临时节点
		other.Next = &tmp        // 首节点的next 指向临时节点
		other = &tmp             // other 向后移动一格
	}
	return root.Next

}

// string to link
func strToLink(str string) *ListNode {
	if len(str) > 0 {
		v1, _ := strconv.Atoi(string(str[0]))
		root := ListNode{v1, nil}
		other := &root
		for i := 1; i < len(str); i++ {
			v2, _ := strconv.Atoi(string(str[i]))
			tmp := ListNode{v2, nil}
			other.Next = &tmp
			other = &tmp
		}
		return &root
	}
	return nil
}

func reserve(s string) string {
	var arr = []rune(s)
	for begin, end := 0, len(arr)-1; begin <= end; begin, end = begin+1, end-1 {
		arr[begin], arr[end] = arr[end], arr[begin]
	}
	return string(arr)
}
